package com.javaspeak.designpatterns.go4.structural.decorator;

/**
 * This class is a Decorator. It holds a reference to another decorator.
 * The decorators implement Transformer.  The reference to another decorator
 * can be added by calling addDecoration( Transformer<String> transformer).
 * <p>
 * After calling transform on some input data it calls transform on the
 * decorator it references.
 * <p>
 * In this way a chain of decorators (transformers) is created, the last
 * transformer in the chain holding no reference to a decorator.
 *
 * @author John Dickerson
 */
public class RemoveMultipleSpacesTransformer implements Transformer<String> {

    private Transformer<String> transformer;


    /* (non-Javadoc)
     * @see com.javaspeak.designpatterns.go4.structural.decorator.
     *      Transformer#addDecoration(com.javaspeak.designpatterns.go4.
     *              structural.decorator.Transformer)
     */
    @Override
    public void addDecoration( Transformer<String> transformer) {

        this.transformer = transformer;
    }


    /* (non-Javadoc)
     * @see com.javaspeak.designpatterns.go4.structural.decorator.
     *      Transformer#transform(java.lang.Object)
     */
    @Override
    public String transform( String input ) {

        String output = input.replaceAll( "\\s+", " " );

        if ( this.transformer != null ){

            return this.transform( output );
        }

        return output;
    }
}
